package com.ld.common.listener;

import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import com.ld.common.config.ProjectSecurityKey;
import com.ld.common.config.web.LdGlobal;
import com.ld.common.plugin.PluginManager;
import com.ld.common.util.SharedVarsUtil;
import com.ld.common.util.notice.NoticeUtil;
import com.ld.common.util.notice.service.NoticeSendService;
import com.ld.common.util.notice.service.ProjectNoticeSendService;
import com.ld.common.util.security.ProjectSecurityUtil;
import com.ld.shieldsb.common.core.io.PropertiesUtils;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.util.BeetlUtil;
import com.ld.version.Version;

import lombok.extern.slf4j.Slf4j;

/**
 * 启动的优先级比在通过@Configuration中配置ServletContextListener要高
 * 
 * @ClassName WebListener
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2018年12月13日 下午4:42:39
 *
 */
@Component
@Slf4j
public class WebListener implements DisposableBean, InitializingBean, ServletContextAware {

    protected String adminPath = LdGlobal.PROJECT_ADMIN_S;
    protected String frontPath = LdGlobal.PROJECT_FRONT_S;

    @Override
    public void setServletContext(ServletContext context) {
        log.warn("========WebListener初始化。。。========");
        log.warn("插件加载开始……");
        PluginManager.init(); // 插件初始化
        log.warn("插件加载完成！");
        // 异步加载插件,true设为守护线程
        new Timer(true).schedule(new TimerTask() {
            @Override
            public void run() {
            }
        }, 100);
        // // System.out.println("@WebListener:"+companyShieldService);

        Properties props = PropertiesUtils.getInstance().getProperties();

        props.entrySet().stream().forEach(entry -> {
            context.setAttribute(entry.getKey() + "", entry.getValue()); // 赋值到上下文中
        });

        String ctxPath = context.getContextPath();
        // servletContextPath,默认""
        context.setAttribute("ctxPath", ctxPath); // 项目路径
        context.setAttribute("ctxPathA", ctxPath + adminPath); // 后台路径(不包含域名、端口)
        context.setAttribute("ctxPathF", ctxPath + frontPath); // 前台路径(不包含域名、端口)

        // 项目发布,当前运行环境的绝对路径,jar包\war包运行获取不到
        String realPath = context.getRealPath("/");
        log.warn(realPath);
        context.setAttribute("realPath", realPath != null ? realPath.replaceFirst("/", "") : "");

        // beetl全局变量注入
        BeetlUtil.setSharedVars("ctxPath", ctxPath); // 项目路径
        BeetlUtil.setSharedVars("ctxPathA", ctxPath + adminPath);// 后台路径(不包含域名、端口)
        BeetlUtil.setSharedVars("ctxPathF", ctxPath + frontPath); // 前台路径(不包含域名、端口)
        BeetlUtil.setSharedVars("PROJECT_ADMIN_URL", LdGlobal.getProjectAdminURL());// 后台URL
        BeetlUtil.setSharedVars("PROJECT_FRONT_URL", LdGlobal.getProjectFrontURL()); // 前台URL

        // SharedVarsUtil全局变量注入
        SharedVarsUtil.setSharedVars("ctxPath", ctxPath); // 项目路径
        SharedVarsUtil.setSharedVars("ctxPathA", ctxPath + adminPath);// 后台路径(不包含域名、端口)
        SharedVarsUtil.setSharedVars("ctxPathF", ctxPath + frontPath); // 前台路径(不包含域名、端口)
        SharedVarsUtil.setSharedVars("PROJECT_ADMIN_URL", LdGlobal.getProjectAdminURL());// 后台URL
        SharedVarsUtil.setSharedVars("PROJECT_FRONT_URL", LdGlobal.getProjectFrontURL()); // 前台URL

        PropertiesModel.registerContext(context); // 注册上下文变量到配置文件Model中
        context.setAttribute("version", Version.VERSION);

        // 注册通知发送类
        NoticeUtil.registerService(NoticeSendService.getInstance(ProjectNoticeSendService.class));

        ProjectSecurityUtil.load(new ProjectSecurityKey());

//        try {
        // 使用了common-io实现的方式
//            ProjectFileListenerUtil.register();
//            FileChangedListenerManager.start(ProjectFileListenerUtil.KEY_CODE);
//        } catch (Exception e) {
//            log.error("监听文件失败！", e);
//        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public void destroy() throws Exception {
        log.warn("========WebListener销毁。。。========");
        PluginManager.destroy(); // 销毁插件
        NoticeUtil.shutdown(); // 销毁
    }

}